package com.zaoshui.hudada.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.zaoshui.hudada.annotation.AuthCheck;
import com.zaoshui.hudada.common.BaseResponse;
import com.zaoshui.hudada.common.DeleteRequest;
import com.zaoshui.hudada.common.ErrorCode;
import com.zaoshui.hudada.common.ResultUtils;
import com.zaoshui.hudada.constant.UserConstant;
import com.zaoshui.hudada.exception.BusinessException;
import com.zaoshui.hudada.exception.ThrowUtils;
import com.zaoshui.hudada.manager.AIManager;
import com.zaoshui.hudada.model.dto.question.*;
import com.zaoshui.hudada.model.entity.App;
import com.zaoshui.hudada.model.entity.Question;
import com.zaoshui.hudada.model.entity.User;
import com.zaoshui.hudada.model.enums.AppTypeEnum;
import com.zaoshui.hudada.model.vo.QuestionVO;
import com.zaoshui.hudada.service.AppService;
import com.zaoshui.hudada.service.QuestionService;
import com.zaoshui.hudada.service.UserService;
import com.zhipu.oapi.service.v4.model.ModelData;
import io.reactivex.Flowable;
import io.reactivex.Scheduler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * APP 控制器
 */
@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    private AIManager aiManager;

    @Resource
    private AppService appService;

    @Resource
    private Scheduler scheduler;

    // 定义Caffeine缓存
    private final Cache<String, String> caffeineCache = Caffeine.newBuilder().initialCapacity(1024)
            .expireAfterAccess(5L, TimeUnit.DAYS)
            .build();


    // region 增删改查

    /**
     * 创建
     *
     * @param questionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest, HttpServletRequest request) {
        if (questionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);
        //将集合转为json对象
        if (questionAddRequest.getQuestionContent() != null) {
            question.setQuestionContent(JSONUtil.toJsonStr(questionAddRequest.getQuestionContent()));
        }
        //校验参数
        questionService.validQuestion(question, true);
        User loginUser = userService.getLoginUser(request);
        question.setUserId(loginUser.getId());
        boolean result = questionService.save(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newQuestionId = question.getId();
        return ResultUtils.success(newQuestionId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = questionService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        //将集合转为json对象
        if (questionUpdateRequest.getQuestionContent() != null) {
            question.setQuestionContent(JSONUtil.toJsonStr(questionUpdateRequest.getQuestionContent()));
        }
        // 参数校验
        questionService.validQuestion(question, false);
        long id = questionUpdateRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param questionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrquestioner(questionQueryRequest));
        return ResultUtils.success(questionPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrquestioner(questionQueryRequest));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                                 HttpServletRequest request) {
        if (questionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrquestioner(questionQueryRequest));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    // endregion


    /**
     * 编辑
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);
        //集合转json
        if (questionEditRequest.getQuestionContent() != null) {
            question.setQuestionContent(JSONUtil.toJsonStr(questionEditRequest.getQuestionContent()));
        }
        // 参数校验
        questionService.validQuestion(question, false);
        User loginUser = userService.getLoginUser(request);
        long id = questionEditRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = questionService.updateById(question);

        //删除缓存
        String prefix = oldQuestion.getAppId() + ""; // 你希望删除的前缀
        // 获取缓存的映射视图
        ConcurrentMap<String, String> map = caffeineCache.asMap();
        // 遍历并删除符合前缀的key
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            String key = entry.getKey();
            if (key.startsWith(prefix)) {
                // 删除符合前缀的key
                caffeineCache.invalidate(key);
                // 注意：调用invalidate后，你可能不需要从迭代器中显式删除该元素，因为invalidate会从缓存中删除它
                // 但如果你需要确保迭代器不再包含该元素，可以调用iterator.remove()
                iterator.remove(); // 注意：这一步在某些情况下可能不是必要的
            }
        }
        return ResultUtils.success(result);
    }

    // region AI生成题目

    private static final String SYSTEM_MESSAGE = "你是一位严谨的出题专家，我会给你如下信息：\n" +
            "\n" +
            "```\n" +
            "应用名称，\n" +
            "【【【应用描述】】】，\n" +
            "应用类别，\n" +
            "要生成的题目数，\n" +
            "每个题目的选项数\n" +
            "```\n" +
            "\n" +
            "请你根据上述应用名称、应用描述、应用类别信息，按照以下步骤来出题：\n" +
            "1. 要求：题目和选项尽可能地短，题目不要包含序号，每题的选项数以我提供的为主，题目不能重复\n" +
            "2. 严格按照下面的 json 格式输出题目和选项\n" +
            "\n" +
            "```\n" +
            "[{\"options\":[{\"value\":\"选项内容\",\"key\":\"A\"},{\"value\":\"\",\"key\":\"B\"}],\"title\":\"题目标题\"}]\n" +
            "\n" +
            "```\n" +
            "\n" +
            "title是题目，options是选项，每个选项的key按照英文字母序(比如 A、B、C、D)以此类推，value是选项内容\n" +
            "3. 检查题目是否包含序号，若包含序号则去除序号\n" +
            "4. 返回的题目列表格式必须为 JSON 数组";

    private String getUserMessage(App app, int questionNum, int optionNum) {
        StringBuilder userMessage = new StringBuilder();
        userMessage.append(app.getAppName()).append("\n");
        userMessage.append("【【【").append(app.getAppDesc()).append("】】】").append("\n");
        userMessage.append(AppTypeEnum.getEnumByValue(app.getAppType()).getText()).append("\n");
        userMessage.append(questionNum).append("\n");
        userMessage.append(optionNum);

        return userMessage.toString();

    }

    /*
     * AI生成题目
     * */
    @PostMapping("/ai_generate")
    public BaseResponse<List<QuestionContentDTO>> aiGenerateQuestion(@RequestBody AiGenerateQuestionRequest aiGenerateQuestionRequest) {
        if (aiGenerateQuestionRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long appId = aiGenerateQuestionRequest.getAppId();
        int questionNumber = aiGenerateQuestionRequest.getQuestionNumber();
        int optionNumber = aiGenerateQuestionRequest.getOptionNumber();
        App app = appService.getById(appId);
        if (app == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        String userMessage = getUserMessage(app, questionNumber, optionNumber);
        String result = aiManager.doSyncRequest(SYSTEM_MESSAGE, userMessage, null);
        int start = result.indexOf("[");
        int last = result.lastIndexOf("]");
        String json = result.substring(start, last + 1);
        List<QuestionContentDTO> questionContentDTOList = JSONUtil.toList(json, QuestionContentDTO.class);
        return ResultUtils.success(questionContentDTOList);
    }

    /*
     * AI实时生成题目
     * */
    @GetMapping("/ai_generate/sse")
    public SseEmitter aiStreamGenerateQuestion(AiGenerateQuestionRequest aiGenerateQuestionRequest) {
        if (aiGenerateQuestionRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long appId = aiGenerateQuestionRequest.getAppId();
        int questionNumber = aiGenerateQuestionRequest.getQuestionNumber();
        int optionNumber = aiGenerateQuestionRequest.getOptionNumber();
        App app = appService.getById(appId);
        if (app == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        String userMessage = getUserMessage(app, questionNumber, optionNumber);
        Flowable<ModelData> flowable = aiManager.doStreamRequest(SYSTEM_MESSAGE, userMessage, null);
        SseEmitter sseEmitter = new SseEmitter(0L);
        AtomicInteger count = new AtomicInteger(0);
        StringBuilder question = new StringBuilder();

        flowable.observeOn(scheduler)
                .map(data -> data.getChoices().get(0).getDelta().getContent())
                .map(data -> data.replaceAll("\\s", ""))
                .filter(StringUtils::isNotBlank)
                .flatMap(data -> {
                    List<Character> list = new ArrayList<>();
                    for (char c : data.toCharArray()) {
                        list.add(c);
                    }
                    return Flowable.fromIterable(list);
                })
                .doOnNext(c -> {
                    if (c == '{') {
                        count.addAndGet(1);
                    }
                    if (count.get() > 0) {
                        question.append(c);
                    }
                    if (c == '}') {
                        count.addAndGet(-1);
                        if (count.get() == 0) {
                            sseEmitter.send(JSONUtil.toJsonStr(question.toString()));
                            question.setLength(0);
                        }
                    }
                })
                .doOnComplete(sseEmitter::complete)
                .subscribe();
        return sseEmitter;
    }


    // endregion

}
